using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Threading;
using System.Globalization;
using Toenda.TFL.Base;
using Toenda.TFL.Data;
using Toenda.Rails.Data;
using Toenda.Rails.System;
using Toenda.Rails.DataContainer;

public partial class _Default : System.Web.UI.Page {
	private DBMaintenance dbm = new DBMaintenance();
	private AccountProvider ap = new AccountProvider();
	private StaticProvider sp = new StaticProvider();
	private ImageProvider ip = new ImageProvider();
	private Tools t = new Tools();
	private ServerPath serverpath = new ServerPath();

	/// <summary>
	/// Page_PreInit
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_PreInit(object sender, EventArgs e) {
		if(File.Exists(ServerPath.Self.Path + @"\index.html")) {
			Response.Redirect("~/index.html");
		}

		HttpBrowserCapabilities hbc = Request.Browser;

		switch(hbc.Type) {
			case "IE":
			case "IE5":
			case "IE6":
			case "IE7":
				this.Page.Theme = "IE7";
				break;

			default:
				this.Page.Theme = "Default";
				break;
		}

		try {
			//if(Session.Count > 0 && ap.CheckSessionExist(Session["Zappr"].ToString())) {
			if(Session.Count > 0 && Session["ZapprUserId"] != null) {
				Account acc = ap.GetAccount(Session["ZapprUserId"].ToString());
				this.Culture = acc.Language;
				this.UICulture = acc.Language.Substring(0, 2);
			}
			else {
				string[] langs = Request.UserLanguages;

				switch(langs[0].ToLower()) {
					case "de":
					case "de-de":
						this.Culture = "de-DE";
						break;

					case "en":
					case "en-us":
					case "en-gb":
						this.Culture = "en-US";
						break;

					default:
						this.Culture = "en-US";
						break;
				}

				this.UICulture = langs[0].Substring(0, 2);
			}
		}
		catch(Exception ex) {
			string s = ex.Message;
			this.Culture = "en-US";
			this.UICulture = "en";
		}
	}
	
	/// <summary>
	/// Page_Load
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e) {
		// read config
		XmlProvider xml = new XmlProvider(ServerPath.Self.Configfile);
		bool bEngineIsRunning = Convert.ToBoolean(Convert.ToInt32(xml.ReadTag("EngineIsOnline")));
		int iSessionHoldingTime = Convert.ToInt32(xml.ReadTag("SessionHoldingTime"));
		int iOldInactiveUserHoldingTimeMonths = Convert.ToInt32(xml.ReadTag("OldInactiveUserHoldingTimeMonths"));

		if(Request.QueryString.Count == 0
		|| (Request.QueryString.GetKey(0) == "id"
		&& Request.QueryString.Get("id").ToString() == "dashboard")) {
			base.Title = xml.ReadTag("WebPageTitle");
		}
		else {
			base.Title = xml.ReadTag("WebPageTitleMain");
		}

		Control ctrl = Page.Master.FindControl("plcMasterVersion");
		ctrl.Controls.Add(new LiteralControl("<!--"));
		ctrl.Controls.Add(new LiteralControl("\n\tPowered by ASP.NET on Rails " + t.GetAssemblyVersion()));
		ctrl.Controls.Add(new LiteralControl("\n\tPowered by Toenda Foundation Library " + AssemblyInfo.Version));
		ctrl.Controls.Add(new LiteralControl("\n\tPowered by ASP.NET Ajax Extension"));
		ctrl.Controls.Add(new LiteralControl("\n\t-->"));

		if(bEngineIsRunning) {
			plcHeaderBox.Controls.Add(LoadControl("Controls/ctrl_header.ascx"));
			plcFooterBox.Controls.Add(LoadControl("Controls/ctrl_footer.ascx"));

			// id
			if(Request.QueryString.Count > 0) {
				switch(Request.QueryString.GetKey(0)) {
					case "id":
						// default actions
						plcPathway.Visible = false;
						plcImagebar.Visible = false;

						string strID = Request.QueryString.Get("ID");

						switch(strID) {
							case "search":
								string tag = "";

								if(Request.QueryString.Get("tag") != null) {
									tag = Request.QueryString.Get("tag");
								}

								Response.Redirect("~/search.aspx?tag=" + tag + "&target=a&type=0");
								break;

							case "dashboard":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_dashboard.ascx"));
								break;

							case "exif":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_exif.ascx"));
								break;

							case "explore":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_explore.ascx"));
								break;

							case "tags":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_tags.ascx"));
								break;

							case "cameras":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_cameras.ascx"));
								break;

							case "sets":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_sets.ascx"));
								break;

							case "favorites":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_favorites.ascx"));
								break;

							case "advise":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_advise.ascx"));
								break;

							case "images":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_images.ascx"));
								break;

							case "upload":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_upload.ascx"));
								break;

							case "profile":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_profile.ascx"));
								break;

							case "account":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_account.ascx"));
								break;

							case "finishaccountclosing":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_finishaccountclosing.ascx"));
								break;

							case "badge":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_badge.ascx"));
								break;

							case "validate":
								if(Request.QueryString.Get("code") != null) {
									string strCode = Request.QueryString.Get("code").ToString();
									Account val = ap.GetAccount(strCode);

									if(val.Username != "" && val.Enabled == false) {
										//val.Enabled = true;
										//ap.SaveAccount(val, "");

										ap.EnableUser(strCode);

										Response.Redirect("~/login.aspx?register=validationsuccessfull");
									}
									else if(val.Enabled == true) {
										Response.Redirect("~/login.aspx?message=UserIsEnabled");
									}
									else {
										Response.Redirect("~/login.aspx?message=IncorrectValidationCode");
									}
								}
								else {
									Response.Redirect("~/login.aspx?message=IncorrectValidationCode");
								}
								break;

							case "logout":
								if(Session.Count > 0 && Session["ZapprUserId"] != null) {
									ap.Logout(Session["Zappr"].ToString());

									Session.RemoveAll();
									Session.Clear();
									Session.Abandon();

									Response.Redirect("~/login.aspx");
								}
								else {
									Response.Redirect("~/login.aspx");
								}
								break;

							// ------- actions -------

							case "_delete":
								ImageItem item = ip.GetImage(Request.QueryString.Get("Photo").ToString());
								Account acc = ap.GetAccount(item.UserID);

								FileInfo info = new FileInfo(
									serverpath.Path + @"\Images\" + item.ImageOriginal
								);
								info.Delete();

								info = new FileInfo(
									serverpath.Path + @"\Images\" + item.Image1024
								);
								info.Delete();

								info = new FileInfo(
									serverpath.Path + @"\Images\" + item.Image500
								);
								info.Delete();

								info = new FileInfo(
									serverpath.Path + @"\Images\" + item.Image240
								);
								info.Delete();

								info = new FileInfo(
									serverpath.Path + @"\Images\" + item.Image100
								);
								info.Delete();

								info = new FileInfo(
									serverpath.Path + @"\Images\" + item.Image75x75
								);
								info.Delete();

								ip.DeleteImage(item.ID);

								//Response.Redirect("~/default.aspx?id=images&user=" + acc.Username);
								Response.Redirect("~/images/" + acc.Username + "/default.aspx");
								break;

							case "_addtosetRedirect":
								Response.Redirect(
									"~/default.aspx?id=_addtoset&photo=" + Request.QueryString.Get("photo")
								);
								break;

							case "_addtoset":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_addtoset.ascx"));
								break;

							case "_editset":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_editset.ascx"));
								break;

							case "_createset":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_createset.ascx"));
								break;

							case "_addtags":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_addtags.ascx"));
								break;

							case "_edit":
								plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_editimage.ascx"));
								break;

							case "_editprofile":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_editprofile.ascx"));
								break;

							case "_sendvulnerability":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/ctrl_sendvulnerability.ascx"));
								break;

							case "_deleteuser":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Admin/ctrl_deleteuser.ascx"));
								break;

							case "_deleteimage":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Admin/ctrl_deleteimage.ascx"));
								break;

							case "_enablepro":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Admin/ctrl_enableproaccount.ascx"));
								break;

							case "_setproexpiredate":
								plcForAll.Visible = false;
								plcForTags.Visible = true;

								plcMain2.Controls.Add(LoadControl("Controls/Admin/ctrl_setproexpiredate.ascx"));
								break;

							default:
								break;
						}

						if(strID != "tags"
						&& strID != "logout"
						&& strID != "_delete"
						&& strID != "_addtoset"
						&& strID != "_editset"
						&& strID != "_createset"
						&& strID != "_sendvulnerability"
						&& strID != "_addtags"
						&& strID != "_edit"
						&& strID != "_editprofile") {
							plcSide.Controls.Add(LoadControl("Controls/Side/ctrl_actions.ascx"));
						}
						break;

					case "user":
						plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_profile.ascx"));

						plcSide.Controls.Add(LoadControl("Controls/Side/ctrl_actions.ascx"));
						break;

					case "item":
						plcPathway.Visible = true;
						plcImagebar.Visible = true;

						plcPathway.Controls.Add(LoadControl("Controls/ctrl_pathway.ascx"));
						plcImagebar.Controls.Add(LoadControl("Controls/ctrl_imagebar.ascx"));

						plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_imageview.ascx"));

						plcSide.Controls.Add(LoadControl("Controls/Side/ctrl_actions.ascx"));
						break;

					case "set":
						plcForAll.Visible = false;
						plcForTags.Visible = true;

						plcMain2.Controls.Add(LoadControl("Controls/Main/ctrl_setview.ascx"));
						break;

					default:
						plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_dashboard.ascx"));
						plcSide.Controls.Add(LoadControl("Controls/Side/ctrl_actions.ascx"));
						break;
				}
			}
			else {
				plcMain.Controls.Add(LoadControl("Controls/Main/ctrl_dashboard.ascx"));
				plcSide.Controls.Add(LoadControl("Controls/Side/ctrl_actions.ascx"));
			}

			// maintenance
			this.DoMaintenanceSteps(
				iSessionHoldingTime, 
				iOldInactiveUserHoldingTimeMonths
			);
		}
	}

	/// <summary>
	/// Do all maintenance steps
	/// </summary>
	/// <param name="sessionHoldingTime"></param>
	/// <param name="oldInactiveUserHoldingTimeMonths"></param>
	private void DoMaintenanceSteps(int sessionHoldingTime, int oldInactiveUserHoldingTimeMonths) {
		// clean up database
		dbm.CheckSessions(sessionHoldingTime);
		dbm.CleanUserTable();
		dbm.CleanUpProAccounts();

		List<List<string>> list = dbm.GetDeleteableUserInfo(oldInactiveUserHoldingTimeMonths);
		this.DeleteImages(list[0]);
		this.DeleteAvatars(list[1]);

		dbm.DeleteAllNonActivatedUser(oldInactiveUserHoldingTimeMonths);
	}

	/// <summary>
	/// DeleteAvatars
	/// </summary>
	/// <param name="listUser"></param>
	private void DeleteAvatars(List<string> listUser) {
		foreach(string s in listUser) {
			FileInfo info = new FileInfo(Server.MapPath("Avatar") + "\\" + s);
			info.Delete();
		}
	}

	/// <summary>
	/// DeleteImages
	/// </summary>
	/// <param name="list"></param>
	private void DeleteImages(List<string> listImages) {
		foreach(string s in listImages) {
			ImageItem item = ip.GetImageByUniqueID(s);

			FileInfo info = new FileInfo(Server.MapPath("Images") + "\\" + item.ImageOriginal);
			info.Delete();

			info = new FileInfo(Server.MapPath("Images") + "\\" + item.Image1024);
			info.Delete();

			info = new FileInfo(Server.MapPath("Images") + "\\" + item.Image500);
			info.Delete();

			info = new FileInfo(Server.MapPath("Images") + "\\" + item.Image240);
			info.Delete();

			info = new FileInfo(Server.MapPath("Images") + "\\" + item.Image100);
			info.Delete();

			info = new FileInfo(Server.MapPath("Images") + "\\" + item.Image75x75);
			info.Delete();
		}
	}
}
